{% load staticfiles %}

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <meta charset="UTF-8"> 
        <link href="{% static 'css/plugins/toastr/toastr.min.css' %}" rel="stylesheet"/>
        <link rel="stylesheet" href="{% static 'js/plugins/jqconsole/css/ansi.css' %}" media="all" />
        <script src="{% static 'js/plugins/jqconsole/js/jquery-1.5.1.js' %}"></script>
        <script src="{% static 'js/plugins/jqconsole/js/jqconsole-2.7.min.js' %}"></script>
        <script src="{% static 'js/plugins/toastr/toastr.min.js' %}"></script>

        <style>
            html, body {
                background-color: #333;
                color: white;
                font-family: monospace;
                margin: 0;
                padding: 0;
            }
            #console {
                width: 100%;
                background-color: black;
                border: 3px solid #CCC;
            }
            .jqconsole {
                padding: 10px;
                padding-bottom: 10px;
            }
            .jqconsole-cursor {
                background-color: #999;
            }
            .jqconsole-blurred .jqconsole-cursor {
                background-color: #666;
            }
            .jqconsole-prompt {
                color: #0d0;
            }
            .jqconsole-old-prompt {
                color: #0b0;
                font-weight: normal;
            }
            .jqconsole-input {
                color: #dd0;
            }
            .jqconsole-output-error {
                color: #F00;
            }
            .jqconsole-output-warning {
                color: #FF0;
            }
            .jqconsole-output-success {
                color: #0D0;
            }
            .jqconsole-old-input {
                color: #bb0;
                font-weight: normal;
            }
            .brace {
                color: #00FFFF;
            }
            .paran {
                color: #FF00FF;
            }
            .bracket {
                color: #FFFF00;
            }
            .jqconsole-composition {
                background-color: red;
            }

            {% if error_msg %}
                .jqconsole-header {
                    color: #F00;
                }
            {% else %}
                .jqconsole-header {
                    color: #0D0;
                }
            {% endif %}
        </style>
        <script>
            // 使用 Django csrf 功能
            $.ajaxSetup({headers: {"X-CSRFToken": '{{ csrf_token }}'}});

            // 初始化全局 (数据库/业务组明细)数组
            inception_databases = new Array();
            inception_business_details = new Array();
            inception_business_ids = new Array();

            // 初始化数据库
            {% for dbmp_inception_database in dbmp_inception_databases %}
                inception_database = new Object();
                inception_database.inception_database_id = {{ dbmp_inception_database.inception_database_id }};
                inception_database.inception_record_id = {{ dbmp_inception_database.inception_record_id }};
                inception_database.mysql_database_id = {{ dbmp_inception_database.mysql_database_id }};
                inception_database.execute_status = {{ dbmp_inception_database.execute_status }};
                inception_database.name = "{{ dbmp_inception_database.name }}";
                inception_database.host = "{{ dbmp_inception_database.host }}";
                inception_database.port = {{ dbmp_inception_database.port }};
                inception_database.business_name = "{{ dbmp_inception_database.business_name }}";
                inception_databases.push(inception_database);
            {% endfor %}

            // 初始化业务组明细
            {% for dbmp_inception_business_detail in dbmp_inception_business_details %}
                inception_business_detail = new Object();
                inception_business_detail.inception_business_detail_id = {{ dbmp_inception_business_detail.inception_business_detail_id }};
                inception_business_detail.inception_business_id = {{ dbmp_inception_business_detail.inception_business_id }};
                inception_business_detail.mysql_business_id = {{ dbmp_inception_business_detail.mysql_business_id }};
                inception_business_detail.execute_status = {{ dbmp_inception_business_detail.execute_status }};
                inception_business_detail.db_name = "{{ dbmp_inception_business_detail.db_name }}";
                inception_business_detail.host = "{{ dbmp_inception_business_detail.host }}";
                inception_business_detail.port = {{ dbmp_inception_business_detail.port }};
                inception_business_detail.business_name = "{{ dbmp_inception_business_detail.business_name }}";
                inception_business_details.push(inception_business_detail);
                // 组成ids数组
                if($.inArray(inception_business_detail.inception_business_id, inception_business_ids) == -1) {
                    inception_business_ids.push(inception_business_detail.inception_business_id);
                }
            {% endfor %}

            $(function() {
                // Creating the console.
                var header = "";
                {% if error_msg %} // 如果过错误信息则显示错误信息
                    {% for msg in error_msg %}
                        header += "{{ msg }} \n";
                    {% endfor %}
                {% endif %}
                header += "执行SQL信息: \n";
                header += "  标签: {{ dbmp_inception_record.tag }}" + "\n";
                header += "  备注: {{ dbmp_inception_record.remark }}" + "\n";
                header += "字符集: {{ dbmp_inception_record.charset }}" + "\n";
                header += " \n";
                window.jqconsole = $("#console").jqconsole(header, "> ");

                // Handle a command.
                var handler = function(command) {
                    jqconsole.Prompt(true, handler, function(command) {
                        // Continue line if can"t compile the command.
                        try {
                            Function(command);
                        } catch (e) {
                            if (/[\[\{\(]$/.test(command)) {
                                return 1;
                            } else {
                                return 0;
                            }
                        }
                        return false;
                    });
                };

                // Initiate the first prompt.
                handler();
                window.jqconsole.Write("====================== 正在执行... ========================= \n", "jqconsole-output-warning");

                // 执行SQL
                var execute_status = {{ dbmp_inception_record.execute_status }};
                if (execute_status == 1 || execute_status == 3 || execute_status == 4) {
                    // 执行业务组SQL审核
                    run_inception({{ dbmp_inception_record.inception_record_id }});
                }
            });

            // 后台调用对业务组执行SQL
            function run_inception(inception_record_id) {
                // 如果数组中没有数据返回
                if(inception_databases.length > 0) { // 执行数据库
                    inception_database = inception_databases.shift();
                    detail_info = "";
                    detail_info += "执行SQL数据库信息: \n";
                    detail_info += "  数据库名: " + inception_database.db_name + "\n";
                    detail_info += "  IP地址: " + inception_database.host + "\n";
                    detail_info += "  端口: " + inception_database.port + "\n";
                    window.jqconsole.Write(detail_info);

                    $.ajax({
                        url: "{% url 'dbmp_inception_database_ajax_run_inception' %}",
                        type: "POST",
                        dataType: "json",
                        data: {
                            inception_database_id: inception_database.inception_database_id
                        }
                    }).done(function(data) { 
                        if(data.is_ok == true) {
                            inception_header = "ID | stage | errLevel | stagestatus | Affected_rows | sequence | backup_dbname | execute_time | sqlsha1 \n";
                            window.jqconsole.Write(inception_header);
                            for(i=0; i<data.inception_info.length; i++) {
                                // 显示执行审核返回的数据
                                inception_body = "";
                                inception_body += data.inception_info[i].ID + " | ";
                                inception_body += data.inception_info[i].stage + " | ";
                                inception_body += data.inception_info[i].errlevel + " | ";
                                inception_body += data.inception_info[i].stagestatus + " | ";
                                inception_body += data.inception_info[i].Affected_rows + " | ";
                                inception_body += data.inception_info[i].sequence + " | ";
                                inception_body += data.inception_info[i].backup_dbname + " | ";
                                inception_body += data.inception_info[i].execute_time + " | ";
                                inception_body += data.inception_info[i].sqlsha1 + " \n";
                                inception_body += "errorMessage: " + data.inception_info[i].errormessage + "\n";
                                inception_body += "SQL: " + data.inception_info[i].SQL + "\n";
                                if(data.inception_info[i].errlevel == 0) {
                                    window.jqconsole.Write(inception_body, "jqconsole-output-success");
                                } else if(data.inception_info[i].errlevel == 1) {
                                    window.jqconsole.Write(inception_body, "jqconsole-output-warning");
                                } else if(data.inception_info[i].errlevel == 2) {
                                    window.jqconsole.Write(inception_body, "jqconsole-output-error");
                                }
                            }
                            // 修改按钮样式
                            if(data.execute_status == 2) { // 执行成功
                                change_parent_database_tr(inception_database.inception_database_id, 'success');
                                change_parent_database_button_ok(inception_database.inception_database_id);
                            } else if(data.execute_status == 3) { // 执行失败
                                change_parent_database_tr(inception_database.inception_database_id, 'danger');
                            }
                        } else {
                            window.jqconsole.Write("  执行SQL失败" + "\n", "jqconsole-output-error");
                        }
                        window.jqconsole.Write(data.err_msg + "\n", "jqconsole-output-error");
                        window.jqconsole.Write("-----------------------------------------");
                        window.jqconsole.Write("-----------------------------------------\n");

                        run_inception(inception_record_id); // 递归执行 SQL执行
                    }).error(function(data) { 
                        window.jqconsole.Write("  请求执行SQL失败" + "\n", "jqconsole-output-error");
                    }); 
                } else if(inception_business_details.length > 0) { // 执行业务组明细
                    // 获得业务明细信息 构造成字符串然后显示
                    inception_business_detail = inception_business_details.shift();
                    detail_info = "";
                    detail_info += "执行SQL业务组明细信息: \n";
                    detail_info += "  业务组名: " + inception_business_detail.business_name + "\n";
                    detail_info += "  数据库名: " + inception_business_detail.db_name + "\n";
                    detail_info += "  IP地址: " + inception_business_detail.host + "\n";
                    detail_info += "  端口: " + inception_business_detail.port + "\n";
                    window.jqconsole.Write(detail_info);
                    
                    $.ajax({
                        url: "{% url 'dbmp_inception_business_detail_ajax_run_inception' %}",
                        type: "POST",
                        dataType: "json",
                        data: {
                            inception_business_detail_id: inception_business_detail.inception_business_detail_id
                        }
                    }).done(function(data) { 
                        if(data.is_ok == true) {
                            inception_header = "ID | stage | errLevel | stagestatus | Affected_rows | sequence | backup_dbname | execute_time | sqlsha1 \n";
                            window.jqconsole.Write(inception_header);
                            for(i=0; i<data.inception_info.length; i++) {
                                // 显示执行审核返回的数据
                                inception_body = "";
                                inception_body += data.inception_info[i].ID + " | ";
                                inception_body += data.inception_info[i].stage + " | ";
                                inception_body += data.inception_info[i].errlevel + " | ";
                                inception_body += data.inception_info[i].stagestatus + " | ";
                                inception_body += data.inception_info[i].Affected_rows + " | ";
                                inception_body += data.inception_info[i].sequence + " | ";
                                inception_body += data.inception_info[i].backup_dbname + " | ";
                                inception_body += data.inception_info[i].execute_time + " | ";
                                inception_body += data.inception_info[i].sqlsha1 + " \n";
                                inception_body += "errorMessage: " + data.inception_info[i].errormessage + "\n";
                                inception_body += "SQL: " + data.inception_info[i].SQL + "\n";
                                if(data.inception_info[i].errlevel == 0) {
                                    window.jqconsole.Write(inception_body, "jqconsole-output-success");
                                } else if(data.inception_info[i].errlevel == 1) {
                                    window.jqconsole.Write(inception_body, "jqconsole-output-warning");
                                } else if(data.inception_info[i].errlevel == 2) {
                                    window.jqconsole.Write(inception_body, "jqconsole-output-error");
                                }
                            }
                          
                        } else {
                            window.jqconsole.Write("  执行SQL失败" + "\n", "jqconsole-output-error");
                        }
                        window.jqconsole.Write(data.err_msg + "\n", "jqconsole-output-error");
                        window.jqconsole.Write("-----------------------------------------");
                        window.jqconsole.Write("-----------------------------------------\n");

                        run_inception(inception_record_id); // 递归执行 SQL执行
                    }).error(function(data) { 
                        window.jqconsole.Write("  请求执行SQL失败" + "\n", "jqconsole-output-error");
                    }); 
                } else { // SQL都执行完了再改变状态
                    check_status(inception_record_id);
                    return false; 退出递归函数
                }
            }

            // 改变inception_record状态
            function check_status(inception_record_id) {
                // 获得执行状态
                execute_status = {{ dbmp_inception_record.execute_status }};
                $.ajax({
                    url: "{% url 'dbmp_inception_record_ajax_check_status' %}",
                    type: "POST",
                    dataType: "json",
                    data: {
                        inception_record_id: inception_record_id
                    }
                }).done(function(data) { 
                    if(data.is_ok == 1){
                        toastr.error('没有记录');
                    } else if(data.is_ok == 2) {
                        if(data.execute_status == execute_status) { // 执行状态不变什么都不操作
                            window.jqconsole.Write("\n  == 执行完成(状态没改变) == " + "\n", "jqconsole-output-warning");
                            toastr.warning("执行完成(状态没改变)");
                        } else if(data.execute_status == 1) { // 没有执行
                            window.jqconsole.Write("\n  == 执行完成(未执行) == " + "\n", "jqconsole-output-warning");
                            toastr.warning("执行完成(未执行)");
                            change_parent_status_label("", "未执行");
                            create_parent_execute_button_label(inception_record_id);
                        } else if(data.execute_status == 2) { // 全部执行成功
                            window.jqconsole.Write("\n  == 执行完成(全部执行成功) == " + "\n", "jqconsole-output-success");
                            toastr.success("执行完成(全部执行成功)");
                            change_parent_status_label("success", "执行成功");
                            remove_parent_execute_button_label(inception_record_id);
                        } else if(data.execute_status == 3) { // 全部执行失败
                            window.jqconsole.Write("\n  == 执行完成(全部执行失败) == " + "\n", "jqconsole-output-error");
                            toastr.error("执行完成(全部执行失败)");
                            change_parent_status_label("danger", "执行失败");
                            create_parent_execute_button_label(inception_record_id);
                        } else if(data.execute_status == 4) { // 只执行了部分
                            window.jqconsole.Write("\n  == 执行完成(部分失败) == " + "\n", "jqconsole-output-warning");
                            toastr.warning("执行完成(部分失败)");
                            change_parent_status_label("warning", "部分失败");
                            create_parent_execute_button_label(inception_record_id);
                        }
                        //改变业务组行样式
                        change_parent_business_row();
                    } else if(data.is_ok == 3) {
                        toastr.error("程序错误");
                    }
                }).error(function(data) { 
                    toastr.error("请求获取审核数据库失败");
                });
            }

            // 改变父窗口的状态标签
            function change_parent_status_label(label_color, value) {
                class_str = "label label-" + label_color;
                attr = $("#execute_status_label", window.parent.document).attr("class");
                $("#execute_status_label", window.parent.document).removeClass(attr);
                $("#execute_status_label", window.parent.document).addClass(class_str);
                $("#execute_status_label", window.parent.document).html(value);
            }

            // 添加父窗口的执行按钮
            function create_parent_execute_button_label(inception_record_id) {
                button_html_str = '';
                button_html_str += '<button id="run_inception_button_all" type="button" class="btn btn-primary btn-outline"';
                button_html_str += '        onclick="run_inception(' + inception_record_id + ')">';
                button_html_str += '    <i class="fa fa-chevron-circle-right"></i>';
                button_html_str += '    执行';
                button_html_str += '</button>';
                $("#run_inception_row_all", window.parent.document).html(button_html_str);
            }

            // 删除父窗口的执行按钮
            function remove_parent_execute_button_label() {
                $("#run_inception_row_all", window.parent.document).remove();
            }

            // 修改父窗口数据库 tr 为成功样式
            function change_parent_database_tr(inception_database_id, class_color) {
                attr = $("#inception_database_" + inception_database_id, window.parent.document).attr("class");
                $("#inception_database_" + inception_database_id, window.parent.document).removeClass(attr);
                $("#inception_database_" + inception_database_id, window.parent.document).addClass(class_color);
            }

            // 修改父窗口数据库 按钮 为成功样式
            function change_parent_database_button_ok(inception_database_id) {
                // 构造成功显示标签
                html_str = "";
                html_str += '<a>';
                html_str += '    <i class="fa fa-check text-navy"></i>';
                html_str += '    成功';
                html_str += '</a>';
                $("#inception_database_button_td_" + inception_database_id, window.parent.document).html(html_str);
            }

            //改变业务组行样式
            function change_parent_business_row() {
                console.log("zaaa");
                for(var i=0; i<inception_business_ids.length; i++) {
                    get_business_execute_status_and_change(inception_business_ids[i]);
                }
            }
            
            // 获得和修改业务组行样式
            function get_business_execute_status_and_change(inception_business_id) {
                $.ajax({
                    url: "{% url 'dbmp_inception_business_ajax_get_execute_status' %}",
                    type: "POST",
                    dataType: "json",
                    data: {
                        inception_business_id: inception_business_id
                    }
                }).done(function(data) { 
                    console.log(data);
                    if(data.execute_status == 1) {
                        change_parent_business_tr(inception_business_id, "");
                    } else if(data.execute_status == 2) {
                        change_parent_business_tr(inception_business_id, "success");
                        remove_parent_business_button(inception_business_id);
                        change_parent_business_button_ok(inception_business_id);
                    } else if(data.execute_status == 3) {
                        change_parent_business_tr(inception_business_id, "danger");
                    } else if(data.execute_status == 4) {
                        change_parent_business_tr(inception_business_id, "warning");
                    } else {
                        window.jqconsole.Write(data.err_msg + "\n", "jqconsole-output-error");
                        toastr.error(data.err_msg);
                    }
                }).error(function(data) { 
                    window.jqconsole.Write("  请求业务组执行状态失败" + "\n", "jqconsole-output-error");
                    toastr.error("请求错误的业务组执行状态");
                }); 
            }

            // 修改父窗口数据库 tr 为成功样式
            function change_parent_business_tr(inception_business_id, class_color) {
                attr = $("#inception_business_" + inception_business_id, window.parent.document).attr("class");
                $("#inception_business_" + inception_business_id, window.parent.document).removeClass(attr);
                $("#inception_business_" + inception_business_id, window.parent.document).addClass(class_color);
            }

            // 移除父窗口业务组按钮
            function remove_parent_business_button(inception_business_id) {
                $("#business_button_" + inception_business_id, window.parent.document).remove();
            }

            // 修改父窗口数据库 按钮 为成功样式
            function change_parent_business_button_ok(inception_business_id) {
                // 构造成功显示标签
                html_str = "";
                html_str += '<a id="business_button_' + inception_business_id + '">';
                html_str += '    <i class="fa fa-check text-navy"></i>';
                html_str += '    成功';
                html_str += '</a>';
                $("#inception_business_button_td_" + inception_business_id, window.parent.document).append(html_str);
            }

        </script>
    </head>
    <body>
        <div id="console"></div>
    </body>
</html>
